﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASPItalia.ModelVirtualCasting.ObjectModel;

namespace ASPItalia.ModelVirtualCasting.Web
{
    public partial class ModifyCandidate : System.Web.UI.Page
    {
        private string nickname
        {
            get { return this.Request.QueryString["nick"]; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(nickname))
                this.SetError("Errore: nickname non specificato, hai per caso provato a taroccare l'url?");
            
            if (!this.IsPostBack && !string.IsNullOrEmpty(this.nickname))
            {
                var candidate = this.GetCandidateByNick();
                if (candidate == null)
                {
                    this.SetError("Errore: candidato inesistente!");
                }
                else
                {
                    this.BindFormData(candidate);
                }
            }
        }

        private void SetError(string errorText)
        {
            this.lblError.Text = errorText;
            this.mvPage.SetActiveView(viewError);
        }

        private Candidate GetCandidateByNick()
        {
            var candidates = ApplicationContext.Current.Candidates;
            Candidate candidate = candidates
                .Where(c => c.NickName.ToLower() == nickname.ToLower()).SingleOrDefault();

            return candidate;
        }

        private void BindFormData(Candidate candidate)
        {
            if (candidate == null)
                throw new ArgumentNullException("candidate");

            this.txtFirstName.Text = candidate.FirstName;
            this.txtLastName.Text = candidate.LastName;
            this.txtBirthDate.Text = candidate.BirthDate.ToShortDateString();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            { 
                // perform save here
            }
        }
    }
}